from rest_framework import serializers
from rest_framework.serializers import StringRelatedField
# class StudentSerializer(serializers.Serializer):  # 继承格式 abc.ABC
#     id = serializers.IntegerField(label='ID', read_only=True)  # id只读
#     name = serializers.CharField(max_length=20, label='学生姓名')  # CharField必须要带 max_length
#     age = serializers.IntegerField(label='学生年龄', required=False)  # required=False非必填字段
#     sex = serializers.IntegerField(label='学生性别')  # 序列器里没有SmallIntegerField 只有IntegerField字段类型
#     c_time = serializers.DateTimeField(label='创建时间')
#     u_time = serializers.DateTimeField(label='修改时间')
#     is_delete = serializers.BooleanField(label='逻辑删除')
from .models import Student, Classes


class StudentSerializer(serializers.ModelSerializer):
    # 将自动渲染的覆盖掉 原来的下拉框也会覆盖掉，所以一般不会这么写
    # classes = StringRelatedField(read_only=True)
    class_name = serializers.CharField(read_only=True, source='classes.name')

    class Meta:
        model = Student  # 指定模型
        fields = '__all__'  # 指定传哪些字段过去
        # 此处的写法和上面是等效的

    # 自定义校验方法, 对指定值进行校验
    #
    # def validate_name(self, value):
    #     if 'py' not in value.lower():
    #         raise serializers.ValidationError('Name Error')
    #     return value

    # 自定义校验方法, 获取所有属性的值
    # def validate(self, attrs):
    #     if 'py' not in attrs['name'].lower():
    #         raise serializers.ValidationError('Name Error')
    #     return attrs


# 指定学生展示字段
class SimpleStudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'name']


class ClassesSerializer(serializers.ModelSerializer):
    student_set = SimpleStudentSerializer(read_only=True, many=True)

    class Meta:
        model = Classes
        fields = '__all__'

        # 实现 0<age<200 的校验  extra_kwargs 给指定属性名添加或者修改参数
        extra_kwargs = {
            'age': {
                'min_value': 0,
                'max_value': 200
            }
        }

    def validate_name(self, value):
        if 'python' not in value:
            raise serializers.ValidationError('班级名必须带python')
        return value



